//
//  AppDelegate.swift
//  TopStock
//
//  Created by dyd on 2017/8/6.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit
//orGPv1YRl76vjeujgqB-ZHHLGRuQ
//41e3b3dcae31f1f531ddef23

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,WXApiDelegate,JPUSHRegisterDelegate{
    let AppID = "wxb4ce4301a703b851" //微信*开放平台 为顶级股权申请的 AppID
    let AppKey = "41e3b3dcae31f1f531ddef23" //极光推送 App Key
    
    var window: UIWindow?
    let request = TSRequestData()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UserDefaults.standard.removeObject(forKey: KRegistrationID)
        setJPUSHRegister(launchOptions: launchOptions)//设置极光推送        
        //modify
        WXApi.registerApp(AppID, enableMTA: true)//微信注册
        UIApplication.shared.statusBarStyle = .`default`
        var rootViewController = UIViewController()
        let _ = checkLoginStatus()
            setNavBarAppearance()
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let tsrootViewController = storyBoard.instantiateViewController(withIdentifier: "RootViewController") as! TSRootViewController
        let navRootView = UINavigationController.init(rootViewController: tsrootViewController)
            rootViewController = navRootView
        window = UIWindow()
        window?.rootViewController = rootViewController
        window?.backgroundColor = UIColor.white
        window?.makeKeyAndVisible()
        return true
    }
    
    func setNavBarAppearance(){
        let navBar=UINavigationBar.appearance()
        navBar.titleTextAttributes = NavBarTitleTextAttributes
        navBar.tintColor = UIColor.black
        navBar.barTintColor = BarTintColor
        UIApplication.shared.statusBarStyle = .lightContent
    }
    
    func checkLoginStatus() -> Bool{
        let requestDic = request.getUserInfo()
        let data = requestDic?["data"] as? NSDictionary
        if data == nil{
            return false
        }else{
            return true
        }
    }
    
    
    func setJPUSHRegister(launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
    {
        if #available(iOS 8.0, *) {
            let type: UInt = UIUserNotificationType.badge.rawValue | UIUserNotificationType.sound.rawValue | UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        } else {
            let type: UInt = UIUserNotificationType.badge.rawValue | UIUserNotificationType.sound.rawValue | UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        JPUSHService.setup(withOption: launchOptions, appKey: AppKey, channel: nil, apsForProduction: false)
    }
    
    //添加处理APNs通知回调方法
    // MARK: - JPUSHRegisterDelegate
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter willPresent");
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter didReceive");
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
        
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }

    
    //注册APNs成功并上报DeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
        JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
            if resCode == 0{
                print("registrationID获取成功：\(String(describing: registrationID))")
                UserDefaults.standard.set(registrationID, forKey: KRegistrationID)
            }else {
                print("registrationID获取失败：\(String(describing: registrationID))")
                UserDefaults.standard.set(JPUSHService.registrationID(), forKey: KRegistrationID)
            }
        }
    }
    
    //实现注册APNs失败接口
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("did Fail To Register For Remote Notifications With Error:\(error)")
    }


    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        
        WXApi.handleOpen(url, delegate: self as WXApiDelegate)
        return true
    }
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        WXApi.handleOpen(url, delegate: self as WXApiDelegate)
        return true
    }
    
    func onResp(_ resp: BaseResp!) {
        if resp.errCode == 0 && resp.type == 0 {//授权成功
            let response = resp as! SendAuthResp
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WXLoginSuccessNotification"), object: response.code)
        }
        
    }
    

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        UIApplication.shared.applicationIconBadgeNumber = 0
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

